#include <49func.h>
typedef struct shareRes_s {
    int flag; //描述当前应该执行A还是B 0-->A 1-->B
    pthread_mutex_t mutex;//保护对flag的访问
} shareRes_t;
void *threadFunc(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    //判断B能否执行
    while(1){
        pthread_mutex_lock(&pShareRes->mutex);
        if(pShareRes->flag == 1){
            pthread_mutex_unlock(&pShareRes->mutex);
            break;
        }
        pthread_mutex_unlock(&pShareRes->mutex);
    }
    printf("B begin!\n");
    sleep(3);
    printf("B end!\n");
}
int main()
{
    pthread_t tid;
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex, NULL);
    pthread_create(&tid,NULL,threadFunc,&shareRes);
    printf("A begin!\n");
    sleep(3);
    printf("A end!\n");
    pthread_mutex_lock(&shareRes.mutex);
    shareRes.flag = 1;
    pthread_mutex_unlock(&shareRes.mutex);
    pthread_join(tid,NULL);
    return 0;
}

